import Request from 'utils/request';

import UploadFileApi from 'services/uploadFileApi';

import FileDataForm from 'models/log/fileDataForm';
import NoticeForm from 'models/log/noticeForm';

export default class LogApi {
  static getAllLogData(search, pagination) {
    const apiName = 'api/loggingevent/list';
    let postData = search.getObject(pagination);
    return Request.post(apiName, postData).then(res => {
      pagination.totalCount = res.rows;
      return res.data;
    });
  }

  static getFileDataList(search, pagination) {
    const apiName = 'api/aqiniufiles/list';
    let postData = search.getObject(pagination);
    return Request.post(apiName, postData).then(res => {
      let fileList = res.data;
      fileList = _.map(fileList, file => {
        file = new FileDataForm(file);
        return file;
      });

      pagination.totalCount = res.rows;
      return fileList;
    });
  }

  static async uploadFile(fileDataForm) {
    let token = await UploadFileApi.getQiniuToken();
    if (_.isError(token)) {
      return Promise.reject(token);
    }

    let data = fileDataForm.getUploadFile();
    return Request.postFileToQiniu({
      file: data.file,
      fileName: data.fileName,
      key: data.key,
      token
    }).then(imgUrl => {
      return imgUrl;
    });
  }

  static delFile(fileData) {
    const apiName = 'api/aqiniufiles/deleteByNames';
    let names = [fileData.fileName];
    return Request.post(apiName, names).then(res => {
      return res.msg;
    });
  }

  static getNoticeList(search, pagination){
    const apiName = 'api/noticetip/list';
    let postData = search.getObject(pagination);
    return Request.post(apiName,postData).then(res=>{
      let noticeList = res.data;
      noticeList = _.map(noticeList, notice => {
        notice = new NoticeForm(notice);
        return notice;
      });

      pagination.totalCount = res.rows;
      return noticeList;
    });
  }

  static addNotice(noticeForm) {
    const apiName = 'api/noticetip/save';

    let postData = noticeForm.getObject();

    return Request.post(apiName, postData).then(res => {
      return res.msg;
    });
  }

  static updateNotice(noticeForm){
    const apiName = 'api/noticetip/update';

    let postData = noticeForm.getObject();

    return Request.post(apiName, postData).then(res => {
      return res.msg;
    });
  }
}
